<template>
  <van-button
    v-if="isFollowed"
    class="follow-btn"
    round
    size="small"
    @click="onFollow"
    :loading="isFollowLoading"
    >已关注</van-button
  >
  <van-button
    v-else
    class="follow-btn"
    type="info"
    color="#3296fa"
    round
    size="small"
    icon="plus"
    @click="onFollow"
    :loading="isFollowLoading"
    >关注</van-button
  >
</template>

<script>
import { deleteFollow, addFollow } from '@/api/user.js'
import { mapState } from 'vuex'

export default {
  name: 'FollowUser',
  // 修改组件的v-model默认的名称
  // 默认props：value
  // 默认自定义事件：input
  model: {
    prop: 'isFollowed',
    event: 'is-follow'
  },
  data() {
    return {
      isFollowLoading: false // loading加载状态
    }
  },
  methods: {
    async onFollow() {
      this.isFollowLoading = true // 开启loading状态
      /**
       * 判断是否登录
       * 登录情况下正常操作
       * 未登录，要求用户先登录
       * */

      if (this.user) {
        try {
          // 1.判断是否关注
          if (this.isFollowed) {
            // 2.关注发起取关请求
            await deleteFollow(this.userId)
          } else {
            // 3.没关注发起关注请求
            await addFollow(this.userId)
          }
        } catch (error) {
          console.log(error)
          let message = '失败,请稍后重试'
          // 判断状态码是否等于400,400表示关注的是自己
          if (error.response && error.response.status === 400) {
            message = '不能关注自己!'
          }
          this.$toast(message)
        }
        // this.article.is_followed = !this.article.is_followed  取反,更新按钮显示
        this.$emit('is-follow', !this.isFollowed)
      } else {
        this.$toast('请先登录')
        this.$router.push('/login')
      }

      this.isFollowLoading = false // 关闭loading状态
    }
  },
  props: {
    // 用户是否关注状态
    isFollowed: {
      type: Boolean,
      required: true
    },
    // 用户ID
    userId: {
      type: [Number, String, Object],
      required: true
    }
  },
  computed: {
    ...mapState(['user'])
  }
}
</script>

<style></style>
